<link href="/css/style.css" rel="stylesheet">
<link href="/css/style-responsive.css" rel="stylesheet">
<link href="/js/advanced-datatable/css/demo_page.css" rel="stylesheet"/>
<link href="/js/advanced-datatable/css/demo_table.css" rel="stylesheet"/>
<link rel="stylesheet" href="/js/data-tables/DT_bootstrap.css"/>
<link href="/css/style.css" rel="stylesheet">
<link href="/css/style-responsive.css" rel="stylesheet">

<body class="panel" style="padding: 0;  margin: 10px; ">
<div class="row" style="padding: 0;  margin: 10px; ">
    <div class="col-sm-12" style="padding: 0;   margin: 10px; ">
        <div class="panel-body">
            <header class="panel-heading" style="height: 50px;">
                <div class="col-md-10">任务类型列表</div>
                <div class="col-md-2  " align="right">
                    <input type="checkbox" id="sellectAll" onchange="onChangeAllSelect()">全选</input>
                    <button onclick="onDeleteAllSelect()">删除</button>
                </div>

            </header>
            <div class="adv-table " id="advtable" style="padding: 0;  ">
                <table class="  table " id="listTable">
                    <thead>
                    <tr>
                        <th width="20%">ID</th>
                        <th width="25%">taskno</th>
                        <th width="25%">type</th>
                        <th width="30%">content</th>
                        <th width="80px">操作</th>
                    </tr>
                    </thead>
                    <tbody id="maintablebody">
                    </tbody>
                </table>
            </div>
            <footer>
                <label>
                    <select class="form-control" id="stepInput" onchange="currentPage = 1;changeStep(false)" size="1"
                            name="hidden-table-info_length" aria-controls="hidden-table-info">
                        <option value="10" selected="selected">10</option>
                        <option value="25">25</option>
                        <option value="50">50</option>
                        <option value="100">100</option>
                    </select> records per page</label>

                <div id="pageLabelDiv" class="dataTables_paginate paging_bootstrap pagination">
                    <ul>
                    </ul>
                </div>
            </footer>
        </div>
    </div>

    <!--	//-----------弹出推送 的窗口------start------------>
    <div class="modal fade" id="taskContentModal" tabindex="-2" role="dialog" aria-labelledby="taskContentModalLabel"
         aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header" style="height: 50px;">
                    <div class="col-md-4">
                        <h4 class="modal-title">Task Content</h4>
                    </div>
                    <div class="col-md-4">

                    </div>
                    <div class="col-md-4">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    </div>
                </div>

                <div class="modal-body row">
                    <div class="col-md-12">
                        <textarea class="form-control" id="contentUI" name="contentUI"
                                  style="height: 400px;"></textarea>
                    </div>
                </div>
                </form>
            </div>
        </div>
    </div>
</div>
<!-- Placed js at the end of the document so the pages load faster -->
<script src="/js/jquery-1.10.2.min.js"></script>
<script src="/js/jquery-ui-1.9.2.custom.min.js"></script>
<script src="/js/jquery-migrate-1.2.1.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
<script src="/js/modernizr.min.js"></script>
<script src="/js/jquery.nicescroll.js"></script>
<!--common scripts for all pages-->
<script src="/js/scripts.js"></script>
<script src="/js/html5shiv.js"></script>
<script src="/js/respond.min.js"></script>

<script>
    var totalCount = 0
    var currentPage = 1
    var step = 10
    var currentId = 0
    var tablebody
    var currentListData
    var adddata
    var host
    var userWithPirvilege
    var currentApiId = -1
    //从API获取数据列表
    function getList(page, tempstep) {
        currentPage = page;
        step = tempstep
        $.get(host + "/upv_task/task_content/list/" + currentPage + "/" + step, null, listToSuccess, "json");
    }
    //页面载入后先获取默认条数的数据
    window.onload = function () {
        host = "http://" + window.location.host
        getList(currentPage, step);
    }
    //从数据库中获取列表成功
    function listToSuccess(response, status, xhr) {

        if (status == "success" && response.reusltCode == "200") {
            currentListData = response.reusltDetail;
            if (currentListData == null) {
                parent.setMainContentHeight(1, 50);
                return
            }
            totalCount = response.totalCount;
            //	console.log(totalCount , response)
            clearDataTable();
            changeStep(true);
            fillTable();
            parent.setMainContentHeight(currentListData.length, 50);
            document.getElementById("sellectAll").checked = "";
            //	getApiUserList();
        } else {
            alert(response);
        }

    }
    function onBodyResize() {

    }
    //清空api user 选择栏
    function clearApiuserTable() {
        apiUserSelect = document.getElementById("allApiUserSelector");

    }


    //清空api user 选择栏
    function onChangeAllSelect() {
        var sellectAllInput = document.getElementById("sellectAll");
        for (var i = 0; ; i++) {
            var currentSelect = document.getElementById("select" + i);
            if (currentSelect == null) {
                break;

            } else {
                currentSelect.checked = sellectAllInput.checked;
            }
        }
    }
    //删除
    function onDeleteAllSelect() {
        var deleteItemList = new Array();
        for (var i = 0; ; i++) {
            var currentSelect = document.getElementById("select" + i);
            if (currentSelect == null) {
                break;

            } else {
                if (currentSelect.checked == true) {
                    deleteItemList = deleteItemList.concat(currentSelect.value);
                } else {
                    for (var j = 0; j < deleteItemList.length; j++) {
                        if (deleteItemList[j] == currentSelect.value) {
                            deleteItemList.splice(j, 1);
                        }

                    }
                }
            }
        }
        if (deleteItemList.length == 0) {
            return;
        }

        if (confirm('确定要删除？')) {
            $.ajax({
                url: host + "/upv_task/task_content/list",
                type: 'put',
                data: "idlist=" + deleteItemList,
                success: listToSuccess
            }); //			$.delete(host + "/upv_task/task_content/" + itemid, null, deleteTaskContentSuccess, "json");
        }
    }

    //采用本地数组中的数据填充表格
    function fillTable() {
        adddata = "";
        if (currentListData == null || currentListData.length == 0) {
            return
        }
        $.each(currentListData, function (index, item) {
            adddata += ("<tr ");
            var start_s = "<u><s>";
            var end_s = "</s></u>";
            //	if(item.enable == 1) {
            start_s = "";
            end_s = "";
            //	}
            adddata += ("  name=" + index + ">");
            adddata += ("<td>" + start_s + item._id + end_s + "</td>");
            adddata += ("<td>" + start_s + item.taskno + end_s + "</td>");
            adddata += ("<td >" + start_s + getPatchType(item.type) + end_s + "</td>");
            adddata += ("<td><a class='btn btn-success btn-sm'  data-toggle='modal'   href='#taskContentModal' onclick='openTaskContent(\"" + item._id + "\")' >content</a></td>");
            adddata += ("<td  align='right'><input type='checkbox' id= 'select" + index + "'  value= '" + item._id + "' />&nbsp;&nbsp;&nbsp;&nbsp;</td>");
//<a  class='btn btn-warning  btn-sm'  onclick=deleteTaskContent(\'" + item._id + "\') >删除</a>
            adddata += "</tr>";

        });
        tablebody.append(adddata);
    }
    function getPatchType(value) {
        switch (value) {
            case 0:
                return "patch";
                break;
            case 1:
                return "schema";
                break;
        }
    }
    //
    function deleteTaskContent(itemid) {
        if (confirm('确定要删除？')) {
            $.ajax({
                url: host + "/upv_task/task_content/" + itemid,
                type: 'DELETE',
                success: deleteTaskContentSuccess
            }); //			$.delete(host + "/upv_task/task_content/" + itemid, null, deleteTaskContentSuccess, "json");
        }
    }

    function deleteTaskContentSuccess(response, status, xhr) {

        if (status == "success" && response.reusltCode == "200") {

            for (var i = 0, n = 0; i < currentListData.length; i++) {
                if (currentListData[i]._id != response.reusltDetail) {
                    currentListData[n++] = currentListData[i];
                }
            }
            currentListData.length -= 1;
            clearDataTable();
            changeStep(true);
            fillTable();
        } else {
            alert(response);
        }

    }
    //清空数据表格
    function clearDataTable() {
        tablebody = $("#maintablebody");
        tablebody.empty();
    }
    //清空表单
    function clearForm() {
        document.getElementById("label").value = "";
        document.getElementById("description").value = "";
        document.getElementById("url").value = "";
    }

    //每页的条数发生改变时  重新计算分页条数
    function changeStep(onlyChangeStep) {
        var pagelabelDiv = $("#pageLabelDiv ul");
        pagelabelDiv.empty();
        var stepinput = document.getElementById("stepInput")
        step = parseInt(stepinput.options[stepinput.selectedIndex].value);
        var pageNum = Math.ceil(totalCount / step);
        if (currentPage <= 1) {
            pagelabelDiv.append('<li class="prev disabled"><a href="#">← Previous</a></li>')
        } else {
            pagelabelDiv.append('<li class="prev" onclick="getList(' + (currentPage - 1) + ',' + step + ')" ><a href="#">← Previous</a></li>')
        }
        if (pageNum > 6) {
            for (var i = 1; i <= pageNum; i++) {
                if ((i) == currentPage) {
                    pagelabelDiv.append('<li class="active"><a   >' + (i) + '</a></li>')
                } else if ((i <= 2)) {
                    pagelabelDiv.append('<li onclick="getList(' + i + ',' + step + ')"><a  href="#">' + (i) + '</a></li>')
                } else if ((i >= currentPage - 1 && (i <= currentPage + 1)) || (i > pageNum - 2)) {
                    pagelabelDiv.append('<li onclick="getList(' + i + ',' + step + ')"><a  href="#">' + (i) + '</a></li>')
                }
            }

        } else {
            for (var i = 1; i <= pageNum; i++) {
                if ((i) == currentPage) {
                    pagelabelDiv.append('<li class="active"><a   >' + (i) + '</a></li>')
                } else {
                    pagelabelDiv.append('<li onclick="getList(' + i + ',' + step + ')"><a  href="#">' + (i) + '</a></li>')
                }
            }
        }
        if (currentPage >= pageNum) {
            pagelabelDiv.append('<li class="next disabled"><a href="#">Next → </a></li>')
        } else {
            pagelabelDiv.append('<li class="next" onclick="getList(' + (currentPage + 1) + ',' + step + ')" ><a href="#">Next → </a></li>')
        }
        if (onlyChangeStep == false) {
            getList(currentPage, step);
        }
    }

    function openTaskContent(taskid) {
        for (var i = 0; i < currentListData.length; i++) {
            if (currentListData[i]._id == taskid) {
                contentUI.value = jsonToString(currentListData[i].content, 1);
                break;
            }
        }
    }

    function jsonToString(obj, level) {
        var THIS = this;
        switch (typeof(obj)) {
            case 'string':
                return getSomeSpace(level) + '"' + obj.replace(/(["\\])/g, '\\$1') + '"';
            case 'array':
                return '[' + obj.map(THIS.jsonToString).join(',') + ']';
            case 'object':
                if (obj instanceof Array) {
                    var strArr = [];
                    var len = obj.length;
                    for (var i = 0; i < len; i++) {
                        strArr.push(THIS.jsonToString(obj[i], level + 1));
                    }
                    return '[' + getSomeSpace(level) + strArr.join(',') + ']';
                } else if (obj == null) {
                    return 'null';

                } else {
                    var string = [];
                    for (var property in obj) string.push("\r" + THIS.jsonToString(property, level + 1) + ':' + THIS.jsonToString(obj[property], level + 1));
                    return '\r' + getSomeSpace(level) + '{' + string.join(',') + '\r' + getSomeSpace(level) + '}';
                }
            case 'number':
                return obj;
            case false:
                return obj;
        }
    }

    function getSomeSpace(level) {
        var result = "";
        for (var i = 0; i < level; i++) {
            result = result + "  "

        }
        return result;
    }
</script>

</body>